import { Base64 } from "js-base64";
import _ from "lodash";

export const hasPerssion = (perssions, userPerssions) => {
  //如果权限为空，则不需要权限
  if (!perssions || perssions.length === 0) {
    return true;
  }
  // 需要的权限与用户拥有的权限比较
  const mergePermissions = _.intersection(perssions, userPerssions);
  // 如果有权限，则返回true
  if (mergePermissions.length > 0) {
    return true;
  }

  //以上都不是则没有权限
  return false;
};

/**
 * 通用校验函数
 */
export const validate = (obj, values) => {
  for (let filed in obj) {
    if (obj[filed].required) {
      if (!values[filed]) {
        return false;
      }
    }
  }
  return true;
};
export const BASE64 = Base64;
export const lodash = _;

/**
 * 浅拷贝
 */
export const cloneForm = (from, to) => {
  if (!(from instanceof Object) || !(to instanceof Object)) {
    //console.error("参数不合法！");
    return from;
  } else {
    let newForm = {};
    for (let key in from) {
      if (from.hasOwnProperty(key)) {
        newForm[key] = to[key];
      }
    }
    return newForm;
  }
};

/**
 * 深拷贝
 */
export const deepClone = (obj: any) => {
  let objClone = Array.isArray(obj) ? [] : {};
  if (obj && typeof obj === "object") {
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        //判断obj[key]是否有对象,如果是，递归复制
        if (obj[key] && typeof obj[key] === "object") {
          objClone[key] = deepClone(obj[key]);
        } else {
          objClone[key] = obj[key];
        }
      }
    }
  }
  return objClone;
};

export const JsonDeepClone = (obj: any) => {
  let newArr: any = []; // 报错 let newArr = [];
  if (Array.isArray(obj)) {
    newArr = [].concat(JSON.parse(JSON.stringify(obj)));
  }
  return newArr;
};

/**
 * 截取数组
 */
export const chunk = (arr: Array<any>, size) => {
  let newArr: Array<any> = [];
  for (let i = 0; i < arr.length; i = i + size) {
    newArr.push(arr.slice(i, i + size));
  }
  return newArr;
};

/**
 * 自动裁剪图片
 */
export const AutoSize = (Img, size) => {
  let img = new Image();
  img.src = Img.src;
  let width = img.width;
  let height = img.height;
  if (width >= height) {
    Img.height = size;
    Img.width = (width * size) / height;
  } else {
    Img.width = size;
    Img.height = (height * size) / width;
  }
};
